<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/11 16:42
 * Modified Time: 2019/7/11 16:42
 * Version: 2.0
 */

namespace App\Modules\Employee\Criterias;

use App\Lib\Facades\FLAuth;
use App\Models\DynamicLike;
use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use function foo\func;
use Illuminate\Support\Facades\DB;

class WxGetVideoDynamicListCrireria extends BaseCriterias
{
    protected $requestData;

    public function __construct($requestData)
    {
        $this->requestData = $requestData;
    }

    public function apply($model, RepositoryInterface $repository)
    {

        $member_id = FLAuth::id();

        $dynamic_like_query = DB::table('dynamic_like')
                ->selectRaw('count(*) as `like`,dynamic_id')
                ->groupBy('dynamic_id');

        $user_dynamic_like_query = DB::table('dynamic_like')
            ->selectRaw('count(*) as `like`,dynamic_id')
            ->where('member_id',$member_id)
            ->groupBy('dynamic_id');



        $select = '
            hx_dynamic.id,
            hx_dynamic.detail,
            hx_dynamic.created_at,
            hx_dynamic_resource.type,
            hx_video.url,
            hx_video.thumb,
            hx_user.nick,
            hx_user.portrait,
            IF(ISNULL(hx_dynamic_like.`like`),0,hx_dynamic_like.`like`) as `like`,
            IF(ISNULL(hx_user_dynamic_like.`like`),0,hx_user_dynamic_like.`like`) as liked
            
        ';

        $where = [];
        $where[] = ['dynamic_resource.type','=',2];
        if(isset($this->requestData['user_id'])){
            $where[] = ['dynamic.user_id','=',$this->requestData['user_id']];
        }


        $model = $model->selectRaw($select)
                        ->leftJoin('dynamic_resource','dynamic_resource.dynamic_id','dynamic.id')
                        ->leftJoin('video','dynamic_resource.resource_id','video.id')
                        ->leftJoin('user','dynamic.user_id','user.id')
            ->leftJoin(\DB::raw("({$dynamic_like_query->toSql()}) as hx_dynamic_like"),function ($join) use($dynamic_like_query){
                $join->mergeBindings($dynamic_like_query)->on('dynamic.id','=','dynamic_like.dynamic_id');
            })
            ->leftJoin(\DB::raw("({$user_dynamic_like_query->toSql()}) as hx_user_dynamic_like"),function ($join) use($user_dynamic_like_query){
                $join->mergeBindings($user_dynamic_like_query)->on('dynamic.id','=','user_dynamic_like.dynamic_id');
            })
                        ->where($where)
                        ;
        return $model;
    }
}